/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package bgu.ppm.dat.model.impl;

import bgu.ppm.dat.model.Field;
import bgu.ppm.dat.model.Pivot;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;

/**
 *
 * @author User
 */
public class FieldUtils {

    public <F> List<Field<?, F>> extractFields(Pivot<F> pivot, F from, String... fieldNames) throws Exception {
        List<Field<?, F>> result = new LinkedList<>();

        Class c = from.getClass();
        int id = 0;
        for (String f : fieldNames) {
            final Method m = c.getMethod("get" + f, c);
            m.setAccessible(true);

            result.add(new AbstractField<Object, F>(pivot, humanized(f), id++, (Class) m.getReturnType()) {
                @Override
                public Object getValue(F o) {
                    try {
                        return m.invoke(o);
                    } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                        throw new RuntimeException(ex);
                    }
                }
            });
        }

        return result;
    }

    public static String humanized(String f) {
        char[] chars = f.toCharArray();
        StringBuilder sb = new StringBuilder(chars[0]);

        for (int i = 1; i < chars.length; i++) {
            if (Character.isUpperCase(chars[i])) {
                sb.append(" ");
            }

            sb.append(chars[i]);
        }

        return sb.toString();
    }
}